package com.woorigil.social.worker.ordering;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.woorigil.social.domain.ProviderCode;
import com.woorigil.social.domain.deal.Deal;
import com.woorigil.social.domain.deal.repository.DealListDao;
import com.woorigil.social.domain.point.DealPointDao;

@Component
public class DealOrdering {
//	private static Logger log = Logger.getLogger(DealOrdering.class);
	@Autowired DealListDao dealListDao;
	@Autowired DealPointDao dealPointDao;
	
	public void execute(int mainCategoryId) {
		List<Deal> deals = dealListDao.selectAllByMainCategory(mainCategoryId);
		
		Map<ProviderCode, List<Deal>> map = orderedGroupByProvider(deals);
		
		int count = 0;
		while (isRemain(map)) {
			int num = (count % 9);
//			System.out.println("mainCategoryId : " + mainCategoryId + " / count : " + count + " / num : " + num);
			if (num == 0 || num == 2 || num == 7) {
				updateOrder(map, ProviderCode.CP, count);
			} else if (num == 1 || num == 6) {
				updateOrder(map, ProviderCode.TM, count);
			} else if (num == 3 || num == 8) {
				updateOrder(map, ProviderCode.WM, count);
			} else if (num == 4) {
				updateOrder(map, ProviderCode.OC, count);
			} else if (num == 5) {
				updateOrder(map, ProviderCode.GP, count);
			}
			count++;
		}
	}

	private Map<ProviderCode, List<Deal>> orderedGroupByProvider(List<Deal> deals) {
		Map<ProviderCode, List<Deal>> map = new HashMap<ProviderCode, List<Deal>>();
		for (ProviderCode providerCode : ProviderCode.values()) {
			map.put(providerCode, new ArrayList<Deal>());
		}
		
		for (Deal deal : deals) {
			List<Deal> orderedDealsGroupByProvider = map.get(deal.getProviderCode());
			orderedDealsGroupByProvider.add(deal);
		}
		return map;
	}
	
	private boolean isRemain(Map<ProviderCode, List<Deal>> map) {
		int size = 0;
		for (Entry<ProviderCode, List<Deal>> entry : map.entrySet()) {
			size = size + entry.getValue().size();
		}
		return size > 0;
	}

	private void updateOrder(Map<ProviderCode, List<Deal>> map, ProviderCode providerCode, int count) {
		List<Deal> list = map.get(providerCode);
		if (list.size() > 0) {
			dealPointDao.updateOrderNo(list.get(0).getId(), count);
			list.remove(0);
		}
	}	
}
